import express from "express";
import cors from "cors";
import path from "path";
import fs from "fs"
import { Database } from "./database";
import multer, { Multer } from "multer"

class Backend {
  database: Database;
  uploadFolder: string
  proResFolder: string
  constructor() {
    this.uploadFolder = path.join(path.dirname(__filename), "upload")
    this.proResFolder = path.join(path.dirname(__filename), "../dist/res/img/")

    this.startBackend();
    this.database = new Database();
  }
  private startBackend() {
    const app = express();
    const port = 8081;
    app.use(cors());
    app.use(express.json());

    app.use("/static", express.static("../frontend"));
    app.use("/preview", express.static("../dist"));
    app.use("/result", express.static("../result"));
    // app.use("/download", express.static("result.tar.gz"));
    app.use("/upload", express.static(this.uploadFolder));

    app.get("/api/download", (req, res) => {
      const filePath = path.join(path.dirname(__filename), "../result.tar.gz")
      console.log(filePath);

      return res.download(filePath)
    })

    app.post("/api/uploadComponent", async (req, res) => {
      // console.log(req.body);
      await this.database.addComponent(req.body);

      res.send({
        success: true,
      });
    });

    app.get("/api/getComponentList", async (req, res) => {
      const data = await this.database.queryComponent();
      res.send({
        data,
      });
    });

    const upload = multer({ dest: this.uploadFolder })

    // upload img for component thumbnails
    app.post("/api/upload", upload.single('file'), (req, res) => {
      const file = req.file
      // const name = req.body.name
      // const email = req.body.email
      if (!file) {
        res.send({
          success: false,
          msg: "unknown file"
        })
        return;
      }
      let newName = new Date().valueOf() + path.extname(file.originalname)
      if (file.filename) {
        fs.renameSync(path.join(this.uploadFolder, file.filename), path.join(this.uploadFolder, newName))
      }


      res.send({
        success: true,
        data: newName
      })
    })

    // upload resources for project 
    app.post("/api/uploadProRes", upload.array('file'), (req, res) => {
      const files = req.files

      if (!files || !files.length) {
        res.send({
          success: false,
          msg: "unknown file"
        })
        return;
      }

      const data = (files as Express.Multer.File[]).map(file => {
        let newName = require("crypto").randomUUID() + path.extname(file.originalname)
        if (file.filename) {
          fs.renameSync(path.join(this.uploadFolder, file.filename), path.join(this.proResFolder, newName))
        }
        return newName
      })

      res.send({
        success: true,
        data
      })
    })

    app.get("/api/delComponent", async (req, res) => {

      if (req.query.id) {
        const data = await this.database.delComponent(req.query.id as number | string);
      }

      res.send({
        success: true
      })
    })

    app.get("/api/getProResFolder", async (req, res) => {
      res.send({
        path: this.proResFolder
      })
    })

    app.listen(port, () => {
      console.log(`listening on port ${port}..`);
    });
  }
}

new Backend();
